<template>
  <div :style="{ position: 'relative', ...containerStyle }">
    <DynamicComp
      v-for="comp in panelJson?.comps"
      :key="comp.id"
      :curComp="comp"
    />
  </div>
</template>
<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import DynamicComp from './dynamic.vue'
import localforageCache from '@/utils/localforage'
import { PanelJsonKeysEnum, MonacoEditEnum } from '@/enums'

let panelJson = ref<TPanel | null>(null)

localforageCache.get(PanelJsonKeysEnum.CUR_PREVIEW_PANEL_JSON_KEY).then((value: any) => {
  if(value) {
    panelJson.value = value
  }
}).catch((e: any) => console.log(e, '预览出错了~~'))

onMounted(() => {
  window.opener.addEventListener(MonacoEditEnum.EDIT_PANEL_JSON, editPanelJsonHandler)
})

onUnmounted(() => {
  window.opener.removeEventListener(MonacoEditEnum.EDIT_PANEL_JSON, editPanelJsonHandler)
})

function editPanelJsonHandler(e: any) {
  panelJson.value = e.detail
}

let containerStyle = computed(() => {
  try {
    if(panelJson?.value) {
      return {
        width: panelJson.value.container.width + 'px',
        height: panelJson.value.container.height + 'px',
        backgroundColor: panelJson.value.container.backgroundColor,
        backgroundImage: `url(${panelJson.value.container.backgroundImage})`,
        backgroundSize: '100% 100%'
      }
    }
  } catch(e: any) {
    console.log(e, '预览出错~~')
    return {
      width: '100vw',
      height: '100vh',
      backgroundColor: '#101014',
      backgroundImage: '',
      backgroundSize: ''
    }
  }
})
</script>